package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private EmpService empService;

    @PostMapping
    public Result login(@RequestBody Emp emp) {
        //1. 调用service进行登陆校验
        Emp empData = empService.getByUsernameAndPassword(emp.getUsername(), emp.getPassword());
        if (empData == null) {
            return Result.error("用户名或者密码错误");
        }

        //2. 生成jwt token
        Map<String, Object> map = new HashMap<>();
        map.put("id", empData.getId());
        map.put("username", empData.getUsername());
        map.put("name", empData.getName());
        String token = JwtUtils.generateJwt(map);

        //3. 返回
        return Result.success(token);
    }
}